package com.example.yiwei.crm.view.activity.menuActivity;


import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import android.widget.Toast;

import com.example.yiwei.crm.R;
import com.example.yiwei.crm.base.baseClass;
import com.example.yiwei.crm.data.QXData;
import com.example.yiwei.crm.entity.VersionEntity;
import com.example.yiwei.crm.json.QXjson;
import com.example.yiwei.crm.json.VersionJson;
import com.example.yiwei.crm.util.NetWorkUtils;
import com.example.yiwei.crm.util.SC;
import com.example.yiwei.crm.view.activity.coordinationActivity.UpdatePasswordActivity;
import com.example.yiwei.crm.view.activity.jdjycooractivity.JDJYCoorActivity;
import com.example.yiwei.crm.view.activity.jtCustomer.JDcoorActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

public class LoginActivity2 extends AppCompatActivity {
    String BOOLEAN;
    String username1;
    String password1;
    String result;
    SharedPreferences sp;
    VersionEntity versionEntity;
    public static  LoginActivity2 a ;
    AlertDialog.Builder builder2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login2);
        a = this;
        sp = getSharedPreferences("login", Context.MODE_PRIVATE);
        username1 = sp.getString("username", null);
        password1 = sp.getString("password", null);
        if (username1==null||password1==null){
            Intent intent = new Intent(LoginActivity2.this,LoginActivity.class);
            startActivity(intent);
            finish();
        }else {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    JSONObject json = new JSONObject();
                    try {
                        SC sc = new SC();
                        JSONObject object1 = sc.storage(sp);
                        String json1 = object1.toString();
                        json.put("KEYDATA", username1 + "," + password1);
                        String sjson = json.toString();
                        result = NetWorkUtils.getCount(baseClass.log_URL, sjson);
                        JSONObject object = new JSONObject(result);
                        BOOLEAN = object.getString("result");
                        String result= NetWorkUtils.getCount(baseClass.find_qx_URL,json1);
                        QXData.creat();
                        QXData.list = QXjson.get(result);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if ("success".equals(BOOLEAN)) {
                                    final String UAB06  = sp.getString("UAB06",null);
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            JSONObject object2 = new JSONObject();
                                            try {
                                                object2.put("APP03",2);
                                                object2.put("APP04",2);
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                            String json = object2.toString();
                                            String result = NetWorkUtils.getCount(baseClass.get_Vresion_URL,json);
                                            Log.d("result = ",result);
                                            versionEntity = VersionJson.getVersion(result);
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    String str1 = null;
                                                    try {
                                                        str1 = getVersionName();
                                                        double a = Double.valueOf(str1);
                                                        double b = Double.valueOf(versionEntity.getVersionname());
                                                        Log.d("cccccc",a+"   "+b);
                                                        if (a<b){
                                                            showandDownLoad();
                                                        }else if ("20".equals(UAB06)||"21".equals(UAB06)){
                                                            Intent intent=new Intent(LoginActivity2.this,JDcoorActivity.class);
                                                            startActivity(intent);
                                                            finish();
                                                        }else if ("22".equals(UAB06)){
                                                            Intent intent=new Intent(LoginActivity2.this,JDJYCoorActivity.class);
                                                            startActivity(intent);
                                                            finish();
                                                        }else {

                                                        }

                                                    } catch (Exception e) {
                                                        e.printStackTrace();
                                                    }
                                                }
                                            });
                                        }
                                    }).start();


                                }else {
                                    Intent intent = new Intent(LoginActivity2.this,LoginActivity.class);
                                    startActivity(intent);
                                    finish();
                                }
                            }
                        });
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Intent intent = new Intent(LoginActivity2.this,LoginActivity.class);
                        startActivity(intent);
                        finish();
                    }
                }
            }).start();
        }
    }
    public String getVersionName() throws Exception
    {
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),0);
        String version = packInfo.versionName;
        return version;
    }
    public void showandDownLoad(){
        AlertDialog.Builder builder;
        builder = new AlertDialog.Builder(new android.view.ContextThemeWrapper(LoginActivity2.this, R.style.custom_dialog));
        builder.setTitle("有新版本");
        builder2 = new AlertDialog.Builder(new android.view.ContextThemeWrapper(LoginActivity2.this, R.style.custom_dialog));
        builder2.setTitle("文件正在下载，请稍后");
        builder.setPositiveButton("更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
//                        File file = new File(Environment.getExternalStorageDirectory() + "/CRM/crm.txt");
//                        final String result = HttpAssist.uploadFile(file,versionEntity.getDownloadURL());
                        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(versionEntity.getDownloadURL()));
                        //设置在什么网络情况下进行下载
                        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
                        //设置通知栏标题
                        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
                        request.setTitle("crm.apk");
                        request.setDescription("CRM正在下载");
                        request.setAllowedOverRoaming(false);
                        //设置文件存放目录
                        File folder = new File(Environment.getExternalStorageDirectory()+"/CRM");
                        if (folder.exists()){
                            File file = new File(Environment.getExternalStorageDirectory()+"/CRM/crm.apk");
                            if (file.exists()){
                                file.delete();
                            }
                        }else {
                            folder.mkdirs();
                        }
                        request.setDestinationInExternalPublicDir("CRM","crm.apk");
                        DownloadManager downManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                        long id = downManager.enqueue(request);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                builder2.setCancelable(false);
                                builder2.show();
                            }
                        });
                    }
                }).start();
            }
        });
        builder.setCancelable(false);
        builder.show();
    }
    public static class DownLoadCompleteReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)){
                long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
//                Log.d("aaaa","cccc");
                File apkfile = new File(Environment.getExternalStorageDirectory()+"/CRM/crm.apk");
                if (!apkfile.exists()) {
                    return;
                }
                // 通过Intent安装APK文件
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
                        "application/vnd.android.package-archive");
                LoginActivity2.a.startActivity(i);
                android.os.Process.killProcess(android.os.Process.myPid());

            }
        }

    }
}
